package com.yc.cloud.common.orm;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author JackGu
 */
@Data
public class CommonPage<T> {

    public static final String DEFAULT_SIZE = "10";
    public static final String DEFAULT_NUM = "1";

    /**
     * 当前页码
     */
    private Integer pageNum;
    /**
     * 每页数量
     */
    private Integer pageSize;
    /**
     * 总页数
     */
    private Integer totalPage;
    /**
     * 总条数
     */
    private Long total;
    /**
     * 分页数据
     */
    private List<T> list;


    /**
     * 将Mybatis plus分页后的list转为分页信息
     */
    public static <T> CommonPage<T> restPage(IPage<T> iPage) {
        CommonPage<T> result = new CommonPage<>();
        result.setTotalPage((int) iPage.getPages());
        result.setPageNum((int) iPage.getCurrent());
        result.setPageSize((int) iPage.getSize());
        result.setTotal(iPage.getTotal());
        result.setList(iPage.getRecords());
        return result;
    }

    /**
     * 将Mybatis plus分页后的list转为分页信息,带vo转换
     */
    public static <T, R> CommonPage<R> restPage(IPage<T> iPage, Class<R> clazz) {
        CommonPage<R> result = new CommonPage<>();
        result.setTotalPage((int) iPage.getPages());
        result.setPageNum((int) iPage.getCurrent());
        result.setPageSize((int) iPage.getSize());
        result.setTotal(iPage.getTotal());
        List<R> voList = iPage.getRecords().stream().map(item -> {
            R vo = null;
            try {
                vo = clazz.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(item, vo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return vo;
        }).collect(Collectors.toList());
        result.setList(voList);
        return result;
    }
}
